package live.betterman.api.controller;

import live.betterman.api.config.security.MyFilterInvocationSecurityMetadataSource;
import live.betterman.common.model.Result;
import live.betterman.system.model.SysPermission;
import live.betterman.system.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * @author: zhudawei
 * @date: 2024/1/11
 * @description:
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private MyFilterInvocationSecurityMetadataSource securityMetadataSource;

    @GetMapping("/")
    public String needPermission() {
        return "need permission!";
    }

    @PostMapping("/add")
    public Result<Boolean> addPermission(@RequestBody SysPermission permission) {
        boolean result = permissionService.saveOrUpdate(permission);
        clearPermissionConfig();
        return Result.success(result);
    }

    /**
     * 清除权限配置
     */
    private void clearPermissionConfig() {
        securityMetadataSource.clearConfigCache();
    }

    @PostMapping("/edit")
    public Result<Boolean> editPermission(@RequestBody SysPermission permission) {
        boolean result = permissionService.saveOrUpdate(permission);
        clearPermissionConfig();
        return Result.success(result);
    }

    @GetMapping("/list")
    public Result<IPage<SysPermission>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String permissionName
    ) {
        Page<SysPermission> page = new Page<>(current, size);
        IPage<SysPermission> result = permissionService.page(page, permissionName);
        return Result.success(result);
    }
}
